package com.jielihaofeng.nettyadvance.rpc.client;

import com.jielihaofeng.nettyadvance.rpc.client.handler.RpcResponseMessageHandler;
import com.jielihaofeng.nettyadvance.rpc.message.RpcRequestMessage;
import com.jielihaofeng.nettyadvance.rpc.protocol.MessageCodecSharable;
import com.jielihaofeng.nettyadvance.rpc.protocol.ProcotolFrameDecoder;
import com.jielihaofeng.nettyadvance.rpc.protocol.SequenceIdGenerator;
import com.jielihaofeng.nettyadvance.rpc.server.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

/**
 * @author Johnnie Wind
 * @description RPC客户端管理
 * @date 2021/11/19 17:34
 */
@Slf4j
public class RpcClientManager {

    private static final Object LOCK = new Object();
    private static Channel channel = null;

    public static void main(String[] args) {
        HelloService service = getProxyService(HelloService.class);
        System.out.println(service.sayHello("jielihaofeng"));
//        System.out.println(service.sayHello("netty"));
//        System.out.println(service.sayHello("hello"));
    }

    /**
     * @description 动态代理
     * @author Johnnie Wind
     * @date 2021/11/22 9:49
     */
    public static <T> T getProxyService(Class<T> serviceClass) {
        ClassLoader loader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        Object o = Proxy.newProxyInstance(loader, interfaces, (proxy, method, args) -> {
            // 将方法调用转换为消息对象
            int sequenceId = SequenceIdGenerator.nextId();
            RpcRequestMessage msg = new RpcRequestMessage(
                    sequenceId,
                    serviceClass.getName(),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args);
            // 发送消息
            Channel channel = getChannel();
            channel.writeAndFlush(msg);
            // 准备一个Promise对象，接收结果，指定异步接收结果的线程
            DefaultPromise<Object> promise = new DefaultPromise<>(channel.eventLoop());
            RpcResponseMessageHandler.PROMISES.put(sequenceId, promise);
            // 等待promise结果
            promise.await();
            if (promise.isSuccess()) {
                return promise.getNow();
            } else {
                return new RuntimeException(promise.cause());
            }
        });

        return (T) o;
    }

    /**
     * @description 获取 Channel（单例模式）
     * @author Johnnie Wind
     * @date 2021/11/22 9:28
     */
    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        synchronized (LOCK) {
            if (channel != null) {
                return channel;
            }
        }

        initChannel();
        return channel;
    }

    /**
     * @description 初始化 Channel
     * @author Johnnie Wind
     * @date 2021/11/22 9:28
     */
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 日志处理器
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        // 共享消息编解码处理器
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();

        // Rpc响应处理器
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 预设长度协议框架解码器
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_HANDLER);
                }
            });
            channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }
}
